<?php

/**
 * Allows module bootstraps to be written like controller plugins so they
 * won't have to register their own plugin just to do stuff at various
 * stages of dispatch.
 *
 * @author     Mon Zafra <monzee at gmail>
 * @copyright  (c)2009 Mon Zafra
 * @category   Mz
 * @package    modules
 * @subpackage modules
 * @license    http://mz-project.googlecode.com/svn/trunk/LICENSE    MIT License
 * @version    SVN: $Id: DispatchHooks.php 29 2009-05-14 15:35:03Z monzee $
 */
class Modules_Plugin_DispatchHooks extends Zend_Controller_Plugin_Abstract
{
    protected $_appBootstrap;
    protected $_modBootstraps;
    protected $_skip = false;
    protected $_module;

    public function __construct($appBootstrap)
    {
        $this->_appBootstrap = $appBootstrap;
    }

    protected function _getBootstrap($module)
    {
        if (null === $this->_modBootstraps) {
            $this->_modBootstraps = $this->_appBootstrap->getResource('modules');
        }
        if (isset($this->_modBootstraps[$module])) {
            return $this->_modBootstraps[$module];
        }
        return false;
    }

    protected function _trigger($bootstrap, $event)
    {
        if (method_exists($bootstrap, $event)) {
            $bootstrap->$event();
        }
    }

    public function routeShutdown(Zend_Controller_Request_Abstract $req)
    {
        $module = $req->getModuleName();
        $bootstrap = $this->_getBootstrap($module);
        !$bootstrap or $this->_trigger($bootstrap, 'routeShutdown');
    }

    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $req)
    {
        $module = $req->getModuleName();
        $bootstrap = $this->_getBootstrap($module);
        !$bootstrap or $this->_trigger($bootstrap, 'dispatchLoopStartup');
    }

    public function preDispatch(Zend_Controller_Request_Abstract $req)
    {
        $module = $req->getModuleName();
        $bootstrap = $this->_getBootstrap($module);
        !$bootstrap or $this->_trigger($bootstrap, 'preDispatch');
    }

    public function postDispatch(Zend_Controller_Request_Abstract $req)
    {
        $module = $req->getModuleName();
        $bootstrap = $this->_getBootstrap($module);
        !$bootstrap or $this->_trigger($bootstrap, 'postDispatch');
        $this->_module = $module;
    }

    public function dispatchLoopShutdown()
    {
        $module = $this->_module;
        $bootstrap = $this->_getBootstrap($module);
        !$bootstrap or $this->_trigger($bootstrap, 'dispatchLoopShutdown');
    }
}